import qs from 'qs';
import axios from './axios';

const post = (url, data, options = {}) => {
  const mergedOptions = {
    ...options,
    url,
    method: 'post',
    data,
  };

  return axios(mergedOptions);
};

const get = (url, options = {}) => {
  const mergedOptions = {
    ...options,
    url,
    method: 'get',
  };

  return axios(mergedOptions);
};

const postForm = (url, data, options = {}) => {
  const mergedOptions = {
    ...options,
    url,
    method: 'post',
    data: qs.stringify(data),
    headers: {
      ...options.headers,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  };

  return axios(mergedOptions);
};

/**
 * @example
 * ajax('/a/b', {
 *  method: 'post',
 *  data: {},
 * })
 *
 * */
const ajax = (url, options = {}) => {
  const { method = 'get', ...rest } = options;
  const lowMethod = ''.toLocaleLowerCase.call(method);
  const mergedOptions = {
    ...rest,
    url,
    method: lowMethod,
  };

  return axios(mergedOptions);
};

ajax.postForm = postForm;
ajax.get = get;
ajax.post = post;

export default ajax;
